package health.lm.com.component_base.scan;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.GsonBuilder;
import com.vondear.rxtool.view.RxToast;

import org.json.JSONObject;

import health.lm.com.data.App;
import health.lm.com.data.HttpCST;
import health.lm.com.network.EasyHttp;
import health.lm.com.network.callback.SimpleCallBack;
import health.lm.com.network.utils.MyApi;
import health.lm.com.router.ARouterConstant;
import me.devilsen.czxing.Scanner;
import me.devilsen.czxing.code.BarcodeFormat;
import me.devilsen.czxing.code.BarcodeReader;
import me.devilsen.czxing.code.CodeResult;
import me.devilsen.czxing.view.ScanActivityDelegate;

/**
 * Created by Android Studio .
 * Project：hlian health.lm.com.component_base.scan
 * Date：2019/8/27 8:50
 * Introduce：二维码扫描工具类
 */
public class ScanUtil {
    //相册按钮,进入选择相册
    private static final int CODE_SELECT_IMAGE = 1;
    private static ScanUtil sScanUtil;
    private ScanCallback mCallback;

    private ScanUtil() {
    }

    public static ScanUtil getInstance() {
        if (null == sScanUtil) sScanUtil = new ScanUtil();
        return sScanUtil;
    }

    @SuppressLint("CheckResult")
    public void homeNavScan(Activity pActivity, ScanCallback pScanCallback) {
        this.mCallback = pScanCallback;
        scan(pActivity);
        //RxPermissions rxPermissions = new RxPermissions(pActivity);
        //rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_APN_SETTINGS
        //        , Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(b -> {
        //    if (b) scan(pActivity);
        //    else RxToast.normal("打开相机失败，请前往设置开启相机权限");
        //});

    }

    private void scan(Activity pActivity) {
        Scanner.with(pActivity)
                .showAlbum(false)
                //.setBorderColor(resources.getColor(R.color.box_line))   // 扫码框边框颜色
                //.setCornerColor(resources.getColor(R.color.corner))     // 扫码框角颜色
                //.setScanLineColors(scanColors)                          // 扫描线颜色（这是一个渐变颜色）
                .setOnClickAlbumDelegate(new ScanActivityDelegate.OnClickAlbumDelegate() {
                    @Override
                    public void onClickAlbum(Activity activity) {  // 点击右上角的相册按钮
                        Intent albumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        activity.startActivityForResult(albumIntent, CODE_SELECT_IMAGE);
                    }

                    @Override
                    public void onSelectData(int requestCode, Intent data) {  // 选择图片返回的数据
                        if (requestCode == CODE_SELECT_IMAGE) selectPic(pActivity, data);
                    }
                })
                .setOnScanResultDelegate(new ScanActivityDelegate.OnScanDelegate() {
                    @Override
                    public void onScanResult(String result) {
                        //处理
                        dealWithData(pActivity, result);
                    }
                }).start();
    }

    private void selectPic(Activity pActivity, Intent intent) {
        BarcodeReader reader = BarcodeReader.getInstance()/*new BarcodeReader(BarcodeFormat.QR_CODE)*/;
        Uri selectImageUri = intent.getData();
        if (selectImageUri == null) return;
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = pActivity.getContentResolver().query(selectImageUri, filePathColumn, null, null, null);
        if (cursor == null) return;
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        if (bitmap == null) return;

        CodeResult result = reader.read(bitmap);
        if (result == null) {
            Log.e("Scan >>> ", "no code");
            return;
        } else {
            Log.e("Scan >>> ", result.getText());
        }
        dealWithData(pActivity, result.getText());
        Log.d("ScanResult", result.getText());
    }

    private void dealWithData(Activity pActivity, String data) {
        try {
            Log.d("ScanResult", data);
            ScanResultEntity entity = new GsonBuilder().create().fromJson(data, ScanResultEntity.class);
            switch (entity.getType()) {
                case 1://跳转链接
                    //String url = entity.getKey();
                    //if (url.contains("?")) url = url + "&is_app=1";
                    //else url = url + "?is_app=1";
                    //mWebView.loadUrl(url);
                    break;
                case 2://钱包地址
                    if (entity.getKey().length() != 42)
                        pActivity.runOnUiThread(() -> {
                            RxToast.normal("抱歉，您扫的不是区块链账号");
                        });
                    else {
                        if (null != mCallback) mCallback.result(entity.getKey());
                    }
                    break;
                case 3://核销码 (扫码入场、扫码出场)
                    hexiao(entity.getKey(), entity.getUid());
                    break;
                case 4://线下付款 跳转付款页面
                    ARouter.getInstance().build(ARouterConstant.SweepPayActivity)
                            .withString(ARouterConstant.EVALUATION_ID, entity.getKey()).navigation();
                    break;
            }
        } catch (Exception pE) {
            pE.printStackTrace();
        }
    }

    /**
     * 验证核销码
     *
     * @param activity_id 活动Id
     * @param uid 持码人Uid
     */
    private void hexiao(String activity_id, int uid) {
        JSONObject jsonObject = new JSONObject();
        String json = "";
        try {
            jsonObject.put(HttpCST.ACCESS_TOKEN, App.getModel().getAccess_token());
            jsonObject.put("active_id", activity_id);
            jsonObject.put("uid", uid);
            json = MyApi.getInstance().generateMessage(HttpCST.MODULE_ACTIVE, HttpCST.INTFC_1012, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EasyHttp.post("/").upJson(json).execute(new SimpleCallBack<Object>() {
            @Override
            public void onSuccess(Object pO) {
                ToastUtils.showShort("核销成功");
            }
        });
    }
}
